# coding=utf-8
import threading
from queue import Queue

import requests
from lxml import etree


class QiuBai(object):
    def __init__(self):
        self.temp_url = "https://www.qiushibaike.com/hot/page/{}"
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36"}
        self.url_queue = Queue()
        self.html_queue = Queue()
        self.content_queue = Queue()

    def get_url_list(self):
        for i in range(1, 14):
            self.url_queue.put(self.temp_url.format(i))

    def parse_url(self):
        while True:
            url = self.url_queue.get()
            response = requests.get(url, headers=self.headers)
            print(response)

            if response.status_code != 200:
                self.url_queue.put(url)
            else:
                self.html_queue.put(response.content.decode())
            self.url_queue.task_done()  # 队列技术减1

    def get_content_list(self):
        while True:
            html_str = self.html_queue.get()
            html = etree.HTML(html_str)
            div_list = html.xpath("//div[@id='content-left']/div")
            content_list = []
            for div in div_list:
                item = {}
                item["user_name"] = div.xpath(".//h2/text()")[0].strip()
                item["content"] = [i.strip() for i in div.xpath(".//div[@class='content']/span/text()")]
                content_list.append(item)
            self.content_queue.put(content_list)
            self.html_queue.task_done()

    def save_content_list(self):
        while True:
            content_list = self.content_queue.get()
            for content in content_list:
                # print(content)
                pass
            self.content_queue.task_done()

    def run(self):
        thread_list = []
        # 准备url列表
        t_url = threading.Thread(target=self.get_url_list, daemon=True)
        thread_list.append(t_url)
        # 遍历发送请求，获取响应
        for i in range(3):
            t_parse = threading.Thread(target=self.parse_url, daemon=True)
            thread_list.append(t_parse)
        # 提取数据
        t_content = threading.Thread(target=self.get_content_list, daemon=True)
        thread_list.append(t_content)
        # 保存
        t_save = threading.Thread(target=self.save_content_list, daemon=True)
        thread_list.append(t_save)

        for t in thread_list:
            t.start()

        for q in [self.url_queue, self.html_queue, self.content_queue]:
            q.join()  # 主线程等待


if __name__ == '__main__':
    qb = QiuBai()
    qb.run()
